package com.mayn.action;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.mayn.api.KdniaoApi;
import com.mayn.api.SFApi;
import com.mayn.api.getJdTraceApi;
import com.mayn.common.ShopEntity;

import net.sf.json.JSONObject;

public class updateErrorExpressInfo {

	private static final Logger LOG = LoggerFactory.getLogger(updateErrorExpressInfo.class);

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InitDb();

		LOG.info("数据库初始化成功");
		
		updateJd();
		
		updateSFContinuous();
	}

	public static void InitDb() {
		String dbConfFile = "dbconfig.txt";
		PropKit.use(dbConfFile);
		LOG.info("config load success from " + dbConfFile);
		String jdbcUrl = PropKit.get("jdbcUrl");
		String user = PropKit.get("user");
		String password = PropKit.get("password");
		if (jdbcUrl.length() > 0) {
			C3p0Plugin c3p0Plugin = new C3p0Plugin(jdbcUrl, user, password);
			ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
			c3p0Plugin.start();
			arp.start();
		}
	}

	public static void updateJd() {

		LOG.info("开始更新快递鸟不支持的京东快递信息");
		List<Record> expressList = null;
		String listSql = "SELECT EIS_NO,EIS_POST_TYPE,EIS_STATE FROM express_info_sync WHERE EIS_CREATE_DATETIME BETWEEN date_sub(now(), INTERVAL 3 month) AND date_sub(now(), interval 48 hour) AND EIS_DEL =0 AND EIS_POST_TYPE='JD' AND EIS_STATE IN(0,2) ORDER BY RAND() limit 100";
		LOG.info("sql=" + listSql);
		expressList = Db.find(listSql);
		if (expressList.size() >= 1) {
			LOG.info("共有" + expressList.size() + "个快递单信息需要更新");
			for (int i = 0; i < expressList.size(); i++) {
				String ShipperCode = expressList.get(i).getStr("EIS_POST_TYPE");
				String LogisticCode = expressList.get(i).getStr("EIS_NO");
				//判断是否符合京东快递单号规则
				if(!LogisticCode.startsWith("VE") || (!LogisticCode.contains("-") && LogisticCode.length() != 13)){
					LOG.error("非正常的京东快递单号:" + LogisticCode);
					KdniaoAction.deleteExpressOrder(ShipperCode, LogisticCode);
					continue;
				}
				int state = KdniaoAction.getExpressOrderState(ShipperCode, LogisticCode);
				if (state == 0 || state == 2) {
					ShopEntity se = new ShopEntity();
					int shopId = 2;
					if (shopId > 0) {
						se.setShopId(shopId);
						List<Record> li = null;
						String sql = "SELECT SHOP_ID,SHOP_API_APP_KEY,SHOP_API_ACCESS_TOKEN,SHOP_API_APP_SECRECT FROM shop WHERE SHOP_ID=" + shopId;
						li = Db.find(sql);
						if (li.size() >= 1) {
							se.setShopApiAppKey(li.get(0).getStr("SHOP_API_APP_KEY"));
							se.setShopApiAccessToken(li.get(0).getStr("SHOP_API_ACCESS_TOKEN"));
							se.setShopApiAppSecrect(li.get(0).getStr("SHOP_API_APP_SECRECT"));
						}
					}

					String JsonStr = getJdTraceApi.getJdTraceJson(se, LogisticCode);
					JSONObject JsonObj = JSONObject.fromObject(JsonStr);
					if (JsonObj.containsKey("Success") && JsonObj.getString("Success").equals("true")) {
						JSONObject jo = new JSONObject();
						jo.put("EBusinessID", KdniaoApi.EBusinessID);
						jo.put("ShipperCode", ShipperCode);
						jo.put("LogisticCode", LogisticCode);

						jo.put("Success", JsonObj.getString("Success"));
						jo.put("State", JsonObj.getString("State"));
						jo.put("Traces", JsonObj.getString("Traces"));

						KdniaoAction.saveExpressInfo(jo);
					} else {
						LOG.error("获取不到物流信息" + ShipperCode + "--" + LogisticCode);
					}
				}
			}
		} else {
			LOG.info("没有快递信息需要更新");
			System.exit(0);
		}

	}

	public static void updateSF() {
		LOG.info("开始更新快递鸟不支持的顺丰快递信息");
		List<Record> expressList = null;
		String listSql = "SELECT EIS_NO,EIS_POST_TYPE,EIS_STATE FROM express_info_sync WHERE EIS_CREATE_DATETIME BETWEEN date_sub(now(), INTERVAL 3 month) and date_sub(now(), INTERVAL 48 HOUR) AND EIS_DEL =0 AND EIS_POST_TYPE='SF' AND EIS_STATE IN (0,2) ORDER BY RAND() limit 100";
		LOG.info("sql=" + listSql);
		expressList = Db.find(listSql);
		if (expressList.size() >= 1) {
			LOG.info("共有" + expressList.size() + "个快递单信息需要更新");
			updateSfExpressList(expressList);
		} else {
			LOG.info("没有快递信息需要更新");
			System.exit(0);
		}
	}
	
	public static void updateSfExpressList(List<Record> expressList){
		for (int i = 0; i < expressList.size(); i++) {
			String ShipperCode = expressList.get(i).getStr("EIS_POST_TYPE");
			String LogisticCode = expressList.get(i).getStr("EIS_NO");
			//判断是否符合顺丰快递单号规则
			if(LogisticCode.length() != 12){
				LOG.error("非正常的顺丰快递单号:" + LogisticCode);
				KdniaoAction.deleteExpressOrder(ShipperCode, LogisticCode);
				continue;
			}
			int state = KdniaoAction.getExpressOrderState(ShipperCode, LogisticCode);
			if (state == 0 || state == 2) {
				String JsonStr = SFApi.getSfTraceJson(LogisticCode);
				JSONObject JsonObj = JSONObject.fromObject(JsonStr);
				if (JsonObj.containsKey("Success") && JsonObj.getString("Success").equals("true") && JsonObj.containsKey("State")) {
					JSONObject jo = new JSONObject();
					jo.put("EBusinessID", KdniaoApi.EBusinessID);
					jo.put("ShipperCode", ShipperCode);
					jo.put("LogisticCode", LogisticCode);

					jo.put("Success", JsonObj.getString("Success"));
					jo.put("State", JsonObj.getString("State"));
					jo.put("Traces", JsonObj.getString("Traces"));

					KdniaoAction.saveExpressInfo(jo);
				} else {
					KdniaoAction.deleteExpressOrder(ShipperCode, LogisticCode);
					LOG.error("获取不到物流信息" + ShipperCode + "--" + LogisticCode);
				}
			}
		}
	}
	
	
	/**
	 * 持续运行
	 */
	public static void updateSFContinuous() {

		while (true) {
			updateSF();
		}

	}
	
	/**
	 * 持续运行
	 */
	public static void updateJdContinuous() {

		while (true) {
			updateJd();
		}

	}

}
